package com.warthur.spring.shiro.framework.auth;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.warthur.spring.shiro.common.util.JedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;

import java.io.Serializable;

/**
 * @author warthur
 * @date 2018/09/09
 */
@Slf4j
public class ShiroCacheSessionDAO extends EnterpriseCacheSessionDAO {

    /**
     * 创建session，保存到redis集群中
     */
    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = super.doCreate(session);
        log.info("sessionId: " + sessionId);

        JedisUtils.set("shiro_session_" + sessionId, JSON.toJSONString(session), 1800);

        return sessionId;
    }

    /**
     * 获取session
     * @param sessionId
     * @return
     */
    @Override
    protected Session doReadSession(Serializable sessionId) {
        Session session = super.doReadSession(sessionId);

        if(session == null){
            String value = JedisUtils.get("shiro_session_" + sessionId.toString());
            if (StringUtils.isNotEmpty(value)) {
                session = JSONObject.parseObject(value, Session.class);
            }
        }

        return session;
    }

    /**
     * 更新session
     * @param session
     */
    @Override
    protected void doUpdate(Session session) {
        super.doUpdate(session);

        JedisUtils.set("shiro_session_" + session.getId(), JSON.toJSONString(session), 1800);
    }

    /**
     * 删除失效session
     */
    @Override
    protected void doDelete(Session session) {
        JedisUtils.delete("shiro_session_" + session.getId().toString());
        super.doDelete(session);
    }
}
